<?php
namespace app\plus_exam\controller;
use app\plus_exam\model\History as HistoryModel;
use app\plus_exam\model\School as SchoolModel;
use app\plus_exam\model\Category as CategoryModel;
use app\plus_exam\model\HistoryQuestion;
use app\passport\model\User as UserModel;

/* *
 * 成绩统计
 * */
class History extends Base{
    private $SchoolModel;
    private $HistoryModel;
    private $CategoryModel;
    private $UserModel;
    private $HistoryQuestion;
    const SCORE_90_100 = 0;
    const SCORE_80_89 = 1;
    const SCORE_70_79 = 2;
    const SCORE_60_69 = 3;
    const SCORE_0_59 = 4;

    public function _initialize(){
        parent::_initialize();
        $this->SchoolModel     = new SchoolModel;
        $this->HistoryModel    = new HistoryModel;
        $this->CategoryModel   = new CategoryModel;
        $this->UserModel       = new UserModel;
        $this->HistoryQuestion = new HistoryQuestion;
    }

    //首页
    public function index(){
        $this->isAuth('plus_exam.history.index');
        $pathMaps = [
            ['name'=>'<i class="iconfont icon-home"></i> '.lang('lang_history_ui_title'),'url'=>url('plus_exam/history/index')],
        ];
        $editMenu = [];
        $this->assign('pathMaps',json_encode($pathMaps));
        $this->assign('editMenu',json_encode($editMenu));
        $school_id = input('school_id/d');
        $info      = $this->SchoolModel->find_info($school_id); 
        $where     = ['school_id'=>$school_id,'status'=>1];  
        $list      = $this->HistoryModel->select_lists($where);
        //计算统计结果
        $statistics = $this->get_statistics($list);
        //查询考场
        $school_lists = $this->SchoolModel->select_lists();
        if($school_lists){
            foreach ($school_lists as $key => $value) {
               $exam_array[$key]['href'] = url('plus_exam/history/index',array('school_id'=>$value['id']));
               $exam_array[$key]['text'] = $value['name'];
               $exam_array[$key]['id']   = $value['id'];
            }
            $exam_json = $exam_array; 
        }
        $this->assign('statistics',$statistics);
        $this->assign('school_id',$school_id);
        $this->assign('info',$info);
        $this->assign('exam_json',$exam_array);
        return $this->fetch();
    }


    //学生列表
    public function lists(){
        $this->isAuth('plus_exam.history.lists');
         $pathMaps = [
            ['name'=>'<i class="iconfont icon-home"></i> '.lang('lang_history_lists_ui_title'),'url'=>url('plus_exam/history/lists')],
        ];
        
        $editMenu = [];
        $this->assign('pathMaps',json_encode($pathMaps));
        $this->assign('editMenu',json_encode($editMenu));
        $school_id    = input('school_id/d');
        $info         = $this->SchoolModel->find_info($school_id);
        $user_id      = null; 
        $where =['A.school_id'=>$school_id]; 
        $list         = $this->HistoryModel->get_exam_user_history($user_id,$where);
        if(!$school_id){
            $list = $this->HistoryModel->get_exam_user_history();
        }
        $count = count($list);
        $school_lists = $this->SchoolModel->select_lists();
        if($school_lists){
            $exam_array = [];
            foreach ($school_lists as $key => $value) {
               $exam_array[$key]['href'] = url('plus_exam/history/lists',['school_id'=>$value['id']]);
               $exam_array[$key]['text'] = $value['name'];
               $exam_array[$key]['id']   = $value['id'];
            }
            $exam_json = $exam_array; 
        }

        $page = $list->render();
        $this->assign('count',$count);
        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('school_id',$school_id);
        $this->assign('info',$info);
        $this->assign('exam_json',$exam_array);
        return $this->fetch();
    }



    //学生列表导出
    public function lists_excel(){
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");  
        header("Content-Disposition:attachment;filename=".date('Ymdhis').".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        $list  = $this->HistoryModel->view('sp_plus_exam_history','score,status,create_time,update_time')
            ->view('sp_passport_face_anyang','name,work,phone','sp_plus_exam_history.user_id = sp_passport_face_anyang.user_id')
            ->where(['sp_plus_exam_history.school_id' => 2,'sp_plus_exam_history.status'=>1])
            ->limit(150000,50000)
            ->select();
        $this->assign('list',$list);
        return $this->fetch();
    }


    private function get_statistics($list) {
        $score_statistics = array(
            'max'            => 0,
            'min'            => 100,
            'average'        => 0,
            'excellent_rate' => 0,
            'pass_rate'      => 0,
        );

        $score_range = array(
            self::SCORE_90_100 => 0,
            self::SCORE_80_89  => 0,
            self::SCORE_70_79  => 0,
            self::SCORE_60_69  => 0,
            self::SCORE_0_59   => 0,
        );

        $total = count($list);
        $invalid_total = 0;
        $total_score = 0;
        foreach ($list as $history) {
            $tmp_score = intval($history['score']);
            if ($tmp_score > 100 || $tmp_score < 0) {
                $invalid_total++;
                continue;
            }

            //得到所有的分数
            $total_score += $tmp_score;
            //获取最大分数
            if ($tmp_score > $score_statistics['max']) {
                $score_statistics['max'] = $tmp_score;
            }
            //获取最小分数
            if ($tmp_score < $score_statistics['min']) {
                $score_statistics['min'] = $tmp_score;
            }
            //统计各个区间
            if (90 <= $tmp_score && $tmp_score <= 100) {
                $score_range[self::SCORE_90_100] += 1;
            } else if (80 <= $tmp_score && $tmp_score <= 89) {
                $score_range[self::SCORE_80_89] += 1;
            } else if (70 <= $tmp_score && $tmp_score <= 79) {
                $score_range[self::SCORE_70_79] += 1;
            } else if (60 <= $tmp_score && $tmp_score < 69) {
                $score_range[self::SCORE_60_69] += 1;
            } else {
                $score_range[self::SCORE_0_59] += 1;
            }

            //优秀率和及格率
            if (90 <= $tmp_score && $tmp_score <= 100) {
                $score_statistics['excellent_rate'] += 1;
            }
            if (60 <= $tmp_score) {
                $score_statistics['pass_rate'] += 1;
            }
        }

        $total_valid = ($total - $invalid_total) * 1.0;//将无效分数去除
        $score_range_rate = array();
        if ($total_valid > 0) {
            $score_statistics['average']        = 1.0 * $total_score / $total_valid;
            $score_statistics['excellent_rate'] = sprintf("%.2f", 100.0 * $score_statistics['excellent_rate'] / $total_valid);
            $score_statistics['pass_rate']      = sprintf("%.2f", 100.0 * $score_statistics['pass_rate'] / $total_valid);
            foreach($score_range as $key => $val) {
                $score_range_rate[$key] = sprintf("%.2f", 100.0 * $val / $total_valid);
            }
        }

        $statistics = array(
            'basic'         => $score_statistics,
            'range'         => $score_range,
            'range_rate'    => $score_range_rate
        );
        return $statistics;
    }


     /**
     * 删除
     * @access public
     */
    public function delete() {
        $this->isAuth('plus_exam.history.delete');
        $id = input('id/d');
        $res = $this->HistoryModel->delete_data($id);
        if (!$res) {
            return json(['code'=>1,'message'=>lang('lang_message_error')]);
        }else{
            $this->HistoryQuestion->delete_data(['history_id' => $id]);
            return json(['code'=>0,'message'=>lang('lang_message_success')]);
        }
    }
}